package edu.upf.da.p2p.sm.client.manager;

import java.util.Hashtable;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import edu.upf.da.p2p.sm.P2PMessage;
import edu.upf.da.p2p.sm.P2PMessageListener;
import edu.upf.da.p2p.sm.client.message.ServiceDefinition;


public class ServiceManager extends P2PMessageListener {

	private static final Log log = LogFactory.getLog(ServiceManager.class);
	private Map<String, String> services;

	public ServiceManager() {
		services = new Hashtable<String,String>();
		//services.put("search", "rienmais@gmail.com");
		//services.put("auth", "rienmais@gmail.com");
	}

	public String getServiceAddress(String string) {
		String addr = services.get(string);
		if(addr == null){
			if(log.isTraceEnabled()){
				log.trace("Esperando a que recibamos un ServiceDefinition para '"+string+"'.");
			}
			try{
				while(addr == null){
					Thread.sleep(100);
					addr = services.get(string);
				}
			}catch(InterruptedException e){}
		}
		return addr;
	}

	public Map<String, String> getAllServices() {
		return services;

	}

	public void processMessage(P2PMessage message) {
		try{
			ServiceDefinition sd = (ServiceDefinition) message;
			services.put(sd.getServiceName(),sd.getFrom());
			if(log.isTraceEnabled()){
				log.trace("Recibido el ServiceDefinition para '"+sd.getServiceName()+"'.");
			}
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error("Error al recibir un ServiceDefinition",e);
			}
		}
	}

}
